package com.lianyi.push.share.udpclient;

import android.text.TextUtils;

import com.lianyi.push.share.listener.UdpSeiviceToClientMessageListener;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;


/**
 * ================================================
 * 作者: leilei
 * 版本: 1.0
 * 创建日期: 2018/4/8 11:20
 * 描述:
 * 修订历史:
 * ================================================
 */
@ChannelHandler.Sharable
public class UdpClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    private UdpSeiviceToClientMessageListener udpSeiviceToClientMessageListener;

    public UdpClientHandler(UdpSeiviceToClientMessageListener listener) {
        this.udpSeiviceToClientMessageListener = listener;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

//    @Override
//    protected void messageReceived(ChannelHandlerContext ctx, DatagramPacket datagramPacket) throws Exception {
//        String response = datagramPacket.content().toString(CharsetUtil.UTF_8);
////        Log.e("客户端收到服务器消息response", "客户端收到服务器消息response:" + response);
//        if (!TextUtils.isEmpty(response)) {
//            EventBus.getDefault().post(new FristTextEvent(response, ConstantValue.UDP_CLIENT_MESSAGE, 0));
//        }
//
//    }

    /**
     * 客户端收到服务器消息
     *
     * @param channelHandlerContext
     * @param datagramPacket
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, DatagramPacket datagramPacket) throws Exception {
        String response = datagramPacket.content().toString(CharsetUtil.UTF_8);
//        Log.e("客户端收到服务器消息response", "客户端收到服务器消息response:" + response);
        if (!TextUtils.isEmpty(response)) {
//            EventBus.getDefault().post(new FristTextEvent(response, ConstantValue.UDP_CLIENT_MESSAGE, 0));
        }
        udpSeiviceToClientMessageListener.serviceToClientListener(channelHandlerContext, datagramPacket);
    }
}
